<template>
  <div class="product-quality-service-item-list-page">
    <!-- 搜索S -->
    <div ref="tableHeaderContainer" class="product-quality-service-item-list-page-search input-with-append-search">
      <el-input v-model.trim="listQueryPage.keyword" :placeholder="$t('task.tip.serviceTip1')" @keyup.enter.native="handleSearch" :style="{ width: '400px' }">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
        <el-button type="primary" slot="append" @click="handleSearch" v-track="Track.formatParams('KEYWORD_SEARCH')">
          {{ $t('common.base.search') }}
        </el-button>
      </el-input>

      <el-button class="ml_12" type="plain-third" @click="handleReset" v-track="Track.formatParams('RESET_SEARCH')">
        {{ $t('common.base.reset') }}
      </el-button>

      <!-- 高级筛选 -->
      <div class="advanced-search-btn">
        <advanced-search
          :fields="searchFieldInfo"
          :search-model="viewportSearchModel"
          :has-save="false"
          :in-common-use="inCommonUse"
          @changeCommonUse="changeCommonUse"
          @search="handleAdvancedSearch"
        />
      </div>
      <!-- 高级筛选 -->
      
    </div>
    <!-- 搜索E -->

    <!-- 表格 -->
    <div class="product-quality-service-item-list-page-table">
      <el-row type="flex" justify="end" class="mb_16">
        <div ref="tableDoContainer">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link cur-point">
              {{ $t('common.base.moreOperator') }}
              <i class="iconfont icon-fdn-select"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="handleExport(false)" v-track="Track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{ $t('common.base.export') }}</div>
              </el-dropdown-item>

              <el-dropdown-item>
                <div @click="handleExport(true)" v-track="Track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{ $t('common.base.exportAll') }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span class="cur-point mar-l-24 more-list" @click="handleSelectColumn" v-track="Track.formatParams('SELECT_COLUMN')">
            {{ $t('common.base.choiceCol') }}
            <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>
      </el-row>

      <el-table 
        v-table-style
        ref="tableRef" 
        v-loading="listLoading" 
        header-row-class-name="common-list-table-header__v2" 
        :data="dataList" 
        stripe 
        border 
        :height="tableContainerHeight"
        @select="handleSelection"
        @select-all="handleSelection"
        :row-key="getRowKeys"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!listLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        </template>
        <el-table-column type="selection" width="48" align="center" fixed="left" :reserve-selection="true"></el-table-column>
        <template v-for="column in columns">
          <el-table-column v-if="column && column.show" :width="column.width" show-overflow-tooltip :key="column.field" :label="column.displayName" :prop="column.field">
            <template slot-scope="scope">
              <template v-if="column.fieldName === 'name'">
                <span class="link-cl" @click="jumpProductDetail(scope.row)">{{ scope.row.productName }}</span>
              </template>
              <template v-else-if="column.fieldName === 'svcEndTime'">
                {{ scope.row.svcEndTime | fmt_form_date }}
              </template>
              <template v-else-if="column.fieldName === 'svcStartTime'">
                {{ scope.row.svcStartTime | fmt_form_date }}
              </template>
              <template v-else-if="column.fieldName === 'serialNumber'">
                {{  scope.row.productSerialNumber }}
              </template>
              <template v-else-if="column.fieldName === 'customer'">
                <span class="link-cl" @click="jumpCustomerDetail(scope.row)">{{ scope.row.customer && scope.row.customer.name || ''}}</span>
              </template>
              <template v-else-if="column.fieldName === 'svcSerialNumber'">
                {{ getWarrantyServiceItemLabel(scope.row[column.fieldName]) }}
              </template>
              <template v-else-if="column.fieldName === 'svcProjectName'">
                {{ getWarrantyServiceItemLabel(scope.row[column.fieldName]) }}
                <serviceProjectNameTag v-if="scope.row.system"/>
              </template>
              <template v-else-if="column.fieldName === 'serviceProjectCycle'">
                {{ scope.row.timeLimit }}{{ scope.row.timeUnit | cycleFun }}
              </template>
              <template v-else-if="column.fieldName === 'linkmanName'">
                {{ scope.row.linkman && scope.row.linkman.name }}
              </template>
              <template v-else-if="column.fieldName === 'createTime'">
                {{ formatDate(scope.row.createTime) }}
              </template>
              <template v-else-if="column.fieldName === 'catalogId'">
                <span class="link-cl" @click="jumpProductType(scope.row)">{{  scope.row.productType }}</span>
              </template>
              <template v-else-if="column.fieldName === 'productTemplate'">
                <span class="link-cl" @click="jumpProductTemplate(scope.row)">{{  scope.row.productTemplateName }}</span>
              </template>
              <template v-else-if="column.fieldName === 'updateTime'">
                {{  formatDate(scope.row.updateTime) }}
              </template>
              <template v-else-if="column.fieldName === 'productCompleteAddress'">
                {{  scope.row.productCompleteAddress }}
              </template>
              <template v-else-if="column.fieldName === 'phone'">
                {{  scope.row.linkman && scope.row.linkman.phone }}
              </template>
              <template v-else-if="column.field === 'tags'">
                {{ scope.row | formatTags }}
              </template>
              <template v-else>
                {{ $formatFormField(column, scope.row) }}
              </template>
            </template>
          </el-table-column>
        </template>
      </el-table>

      <!-- 分页 S -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ total }}</span>
          </i18n>
        </div>
        <el-pagination
          background
          @current-change="handlePageJump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="total">
        </el-pagination>
      </div>
      <!-- 分页 E -->
    </div>

    <!-- start 导出 -->
    <base-export-group
      ref="exportPanel"
      method="post"
      :storage-key="exportStorageKey"
      :group="true"
      :alert="exportAlert"
      :columns="exportColumns"
      action="/excels/customer/warrantyService"
      :validate="checkExportCount"
      :is-show-export-tip="isOpenData"
      :build-params="buildExportParams"
      :needchoose-break="false"
    />
    <!-- end 导出 -->

    <!-- 选择列弹窗 -->
    <biz-select-column ref="selectColumnRef" mode="productWarranty" @save="saveColumnStatus" />
  </div>
</template>
<script>
import Vue from 'vue';
import { ref, onMounted, reactive, toRefs, computed, nextTick, set } from 'vue';

import i18n from '@src/locales';
import _ from 'lodash';
import { toast } from '@src/util/platform';
import { storageGet, storageSet } from '@src/util/storage';
import { isOpenData } from '@src/util/platform'
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';

import { getColumnFields, getSearchFields } from './fields';
import { productFieldFix } from '@src/modules/productV2/public.js';
import { getProductFieldsV2 } from '@src/api/ProductApi';
import { getProductWarrantyList } from '@src/api/productWarrantyApi.ts';
import { smoothQualityInfoFieldForTable } from '@service/QualityInfoService.ts';

import AdvancedSearch from '@src/component/AdvancedSearch/index.vue'
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
import { WarrantyServiceItemLabelEnum } from '@model/enum/LabelEnum'
/* service */
import { convertQualityInfoRemoteDataToFormQualityInfoFieldValue } from '@service/QualityInfoService.ts'

import { jumpProductDetail, jumpCustomerDetail, jumpProductType, jumpProductTemplate } from '@src/modules/productV2/productWarrantyServiceItem/JumpUtil.js';
import { defaultTableData } from '@src/util/table'

import serviceProjectNameTag from '@src/modules/setting/productV2/productQualityManagement/serviceProjectNameTag.vue';
import { Message } from 'element-ui';

export default {
  name: 'product-warranty-item-list-page',
  components: {
    AdvancedSearch,
    serviceProjectNameTag
  },
  filters: {
    cycleFun(value) {
      const newMap = {
        year: i18n.t('common.base.year'),
        month: i18n.t('common.base.month'),
        day: i18n.t('common.base.day2'),
      };

      return newMap[value] || '';
    },
    formatTags ({ customer }) {
      if (!customer) return '';
      if (!customer.tags || !customer.tags.length) return '';
      return customer.tags.map((t) => t.tagName).join(' ');
    }
  },
  setup(props, {}) {
    const tableHeaderContainer = ref();
    const tableDoContainer = ref();
    const tableFooterContainer = ref();
    const selectColumnRef = ref();
    const exportPanel = ref();

    const state = reactive({
      listQueryPage: {
        keyword: '',
      },
      total: 0,
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      listLoading: false,
      dataList: [],
      multipleSelection: [],
      selectedLimit: 500,
      visible: false,
      columns: [],
      searchFieldInfo: getSearchFields(), // 高级搜索字段
      viewportSearchModel: [], // 高级搜索默认值
      inCommonUse: [], // 高级搜索常用字段
      tableContainerHeight: '440px',
      exportColumnsData: [],
      isOpenData,
      exportStorageKey: StorageKeyEnum.ProductQualityExport,
    });

    const Track = Vue.prototype.$track;

    // 获取选中列id
    const selectedIds = computed(() => {
      return state.multipleSelection.map(item => item.id);
    });

    // 导出字段
    const exportColumns = computed(() => {
      const exportColumns = state.columns.map(item => {
        item.export = true
        item.exportAlias = item.fieldName
        item.label = item.displayName
        return item
      });
      
      const exportColumnsData = {
        value: 'productQualityExport',
        label: i18n.t('product.productQualityAssuranceInformation'),
        columns: exportColumns,
      }
      return [exportColumnsData];
    });

    // 勾选Checkbox
    const handleSelection = (selection) => {
      state.multipleSelection = selection;

      nextTick(()=>{
        knowTableContainerHeight()
      })
    };

    // 当前行的key
    const getRowKeys = (row) => {
      return row.id;
    }

    // 获取表头
    const fetchTableHeader = () => {
      getProductFieldsV2({ isFromSetting: false }).then(res => {
        if (!res.succ) {
          state.columns = [...getColumnFields()];
          return toast(message, 'error');
        }

        // 产品系统字段
        let productSystemFields = res.data.filter(item => {
          return item.isSystem && item.fieldName != 'serviceProviders';
        });

        let customerFields = productSystemFields.filter(
          (item) => item.formType == 'customer'
        )[0];
        
        let fixedFields = [];

        // 客户 联系人
        if (customerFields && customerFields.setting.customerOption?.linkman) {
          fixedFields.push({
            displayName: i18n.t('product.type.linkmanName'),
            fieldName: 'linkmanName',
            formType: 'text',
            export: true,
            isSystem: 1
          });

          fixedFields.push({
            displayName: i18n.t('common.form.type.phone'),
            fieldName: 'phone',
            export: true,
            isSystem: 1
          });
        }
        // 客户地址
        if (customerFields && customerFields.setting.customerOption?.address) {
          fixedFields.push({
            displayName: i18n.t('common.form.type.customerAddress'),
            fieldName: 'address',
            export: true,
            formType: 'address',
            isSystem: 1
          });
        }

        productFieldFix.map(item => {
          if (item.isSystem) {
            fixedFields.push(item)
          }
        })

        state.columns = [...smoothQualityInfoFieldForTable(productSystemFields), ...fixedFields, ...getColumnFields()].map(field => {
          return {
            ...field,
            tableName: 'productWarranty',
            field: field.fieldName,
            show: !!field.isSystem,
            width: '160'
          };
        });

        buildColumns();
      });
    };

    // 获取列表数据
    const fetchTableList = async () => {
      state.listLoading = true;
      try {
        const params = {
          ...state.page,
          ...state.listQueryPage
        };

        let ret = await getProductWarrantyList(params);

        const { success, message, result } = ret || {};
        
        if (!success) return toast(message, 'error');

        state.dataList = (result.list || []).map(item => {
          return (
            Object.assign(
              item, 
              convertQualityInfoRemoteDataToFormQualityInfoFieldValue(item, true)
            )
          )
        })
        
        state.total = result.total || 0;
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.listLoading = false;
      }
    };

    const initData = () => {
      state.page.pageNum = 1;
      state.dataList = [];
      fetchTableList();
    }
    // 搜索
    const handleSearch = () => {
      initData()
    }

    // 高级搜索
    const handleAdvancedSearch = (searchModel = {}) => {
      state.listQueryPage = {...state.listQueryPage, systemConditions: searchModel.systemConditions};
      initData();
    };

    // 重置
    const handleReset = () => {
      state.listQueryPage = {
        keyword: '', 
        systemConditions:[]
      };
      state.viewportSearchModel = []
      initData();
    };
    
    // 切换常用字段
    const changeCommonUse = ({fieldName, isChecked}) => {
      const inCommonUseSet = new Set(state.inCommonUse)
      if(isChecked){
        inCommonUseSet.add(fieldName)
      }else {
        inCommonUseSet.delete(fieldName);
      }
      state.inCommonUse = Array.from(inCommonUseSet);
      const storageKey = 'advanced-search-commonUse';
      state.saveDataToStorage(storageKey, state.inCommonUse);
    };

    // 页数改变时触发
    const handlePageJump = pageNum => {
      state.page.pageNum = pageNum;
      state.dataList = [];
      fetchTableList();
    };

    // pageSize 改变时触发
    const handleSizeChange = pageSize => {
      state.page.pageSize = pageSize;
      state.page.pageNum = 1;
      fetchTableList();
    };

    // 导出
    const handleExport = (exportAll) => {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}产品质保数据.xlsx`;
      if (!exportAll) {
        if (!state.multipleSelection.length) {
          return toast(i18n.t('common.base.tip.exportUnChooseTip'));
        }
        ids = selectedIds.value;
      }
      exportPanel.value.open(ids, fileName);
    };

    // 导出提示
    const exportAlert = (result, params = {}) => {
      return toast(result.message);
    };

    // 检测导出数量
    const checkExportCount = (ids, max) => {
      let exportAll = !ids || ids.length == 0;
      return exportAll && state.total > max
        ? t('common.base.tip.exportLimit', { max })
        : null;
    };

    // 构建导出参数
    const buildExportParams = (checkedArr, ids) => {
      let exportAll = !ids || ids.length == 0;

      let params = {
        warrantyExport: checkedArr['productQualityExport'],
        data: exportAll ? '' : ids.join(','),
        exportSearchModel: JSON.stringify({ ...buildParams() }),
        exportTotal: exportAll ? state.total : ids.length
      }
      
      return params;
    };

    // 构建参数
    const buildParams = () => {
      let params = {
        ...state.listQueryPage,
        ...state.page
      };
      return params;
    };

    // ======================= 选择列 S
    // 获取本地localstorage
    const getLocalStorageData = () => {
      const dataStr = storageGet('product_quality_list_key', '{}');
      return JSON.parse(dataStr);
    };

    // 保存数据到本地localstorage
    const saveDataToStorage = (key, value) => {
      const data = getLocalStorageData();
      data[key] = value;
      storageSet('product_quality_list_key', JSON.stringify(data));
    };

    // 点击选择列
    const handleSelectColumn = () => {
      selectColumnRef.value.open(state.columns);
    };

    // 保存选择列
    const saveColumnStatus = event => {
      let columns = event.data || [];

      state.columns = [];
      nextTick(() => {
        state.columns = columns.slice();
        saveColumnStatusToStorage();
      });
      Message.success(i18n.t('common.base.saveSuccess'));
    };

    // 保存选择列配置到本地
    const saveColumnStatusToStorage = () => {
      const localStorageData = getLocalStorageData();
      let columnsStatus = null;

      const columnsList = state.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      saveDataToStorage('columnStatus', columnsStatus);
    };

    // 选择列排序 - 没选中的放到最后
    const buildSortFields = (originFields = [], fieldsMap = {}) => {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    };

    // 构建表格选择列字段
    const buildColumns = async () => {
      // 获取缓存在本地的选择列配置
      const localStorageData = await getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let customFields = [...state.columns];
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        customFields = buildSortFields(customFields, localColumns);
      }

      const columns = customFields.map(col => {
        // 选择列配置 是否勾选（显示）&宽度
        let show = col.show === true;
        let localField = localColumns[col.field]?.field || null;

        if (null != localField) {
          show = localField.show !== false;
        }

        col.show = show;
        return col;
      });

      state.columns = [];
      nextTick(() => {
        state.columns = columns;
      });
    };
    // ======================= 选择列 E

    /**
     * @des 获取列表当前的可滚动高度
     */
    const knowTableContainerHeight = () => {
      let min = 440;
      try {
        let window_ = window.innerHeight;

        let header = tableHeaderContainer.value?.offsetHeight || 0;
        let do_ = tableDoContainer.value?.offsetHeight || 0;
        let footer = tableFooterContainer.value?.offsetHeight || 0;

        min = window_ - header * 1 - do_ * 1 - footer * 1 - 24 - 16 * 3;
        console.log(window_, header, do_, footer, 'window_, header, do_, footer');
        console.log(min, 'min');
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      state.tableContainerHeight = `${min}px`;
    };

    // 获取质保服务项目的多语言label
    const getWarrantyServiceItemLabel = (label) => {
      return WarrantyServiceItemLabelEnum[label] || label
    }

    onMounted(() => {
      fetchTableHeader();
      fetchTableList();

      nextTick(() => {
        knowTableContainerHeight();
        window.onresize = _.debounce(() => {
          knowTableContainerHeight();
        }, 500);
      });
    });

    return {
      defaultTableData,
      tableHeaderContainer,
      tableDoContainer,
      tableFooterContainer,
      selectColumnRef,
      exportPanel,
      exportColumns,
      ...toRefs(state),
      getRowKeys,
      handleSearch,
      handleAdvancedSearch,
      changeCommonUse,
      handleReset,
      Track,
      handleExport,
      exportAlert,
      checkExportCount,
      buildExportParams,
      handleSelectColumn,
      saveColumnStatus,
      handlePageJump,
      handleSelection,
      handleSizeChange,
      formatDate,
      jumpProductDetail,
      jumpCustomerDetail,
      jumpProductType,
      jumpProductTemplate,
      getWarrantyServiceItemLabel,
    };
  },
};
</script>
<style lang="scss" scoped>
.product-quality-service-item-list-page {
  height: 100%;
  overflow: auto;
  padding: 12px;
  &-search {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    padding: 16px;
    margin-bottom: 16px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 0 0 0 rgb(0 0 0 / 6%);
    .advanced-search-btn {
      color: $color-primary-light-6;
      margin-left: 10px;
    }
  }
  &-table {
    background: #fff;
    border-radius: 4px;
    padding: 16px 16px 0;
    .more-list {
      color: #595959;
      &:hover {
        color: $color-primary;
      }
    }
  }
  .link-cl {
    color: $color-primary-light-6;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>